#include "device.h"
#include <pthread.h>
#include <unistd.h>  // 添加 unistd.h 以包含 usleep

#define NUM_THREADS 3
volatile sig_atomic_t keep_running = 1;

void start_thread_pool() {
    DeviceType sensors[] = {SENSOR_TEMP, SENSOR_HUMIDITY, SENSOR_LIGHT};
    pthread_t threads[NUM_THREADS];
    DeviceManager *devices[NUM_THREADS];
    int thread_count = 0;

    printf("启动线程池...\n");
    for (int i = 0; i < NUM_THREADS; i++) {
        devices[i] = find_device_by_type(sensors[i]);
        if (devices[i] == NULL) {
            fprintf(stderr, "未找到传感器: %d\n", sensors[i]);
            continue;
        }
        if (pthread_create(&threads[thread_count], NULL, sensor_update, devices[i]) != 0) {
            fprintf(stderr, "线程创建失败: %s\n", devices[i]->name);
            continue;
        }
        printf("为传感器 %s 创建线程\n", devices[i]->name);
        thread_count++;
    }

    // 等待 SIGINT 信号
    while (keep_running) {
        usleep(100000);  // 0.1 秒检查一次
    }

    // 取消所有线程
    for (int i = 0; i < thread_count; i++) {
        pthread_cancel(threads[i]);
    }

    // 等待线程结束
    for (int i = 0; i < thread_count; i++) {
        pthread_join(threads[i], NULL);
    }
    printf("线程池执行完成\n");
}